"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 服务端工具
Case Name   : 执行gs_dump多次备份序列号后导入，验证值是否一致
Create At   : 2022/06/06
@zou_jialiang0501129488
Description :
    1.新建序列
    2.执行gs_dump并查看导出值
    3.再次执行gs_dump从查看导出值
    4.修改序列值
    5.执行gs_restore进行导入并查看序列值
    6.再次执行gs_restore进行导入并查看序列值
    7.清理环境
Expect      :
    1.新建序列成功
    2.dump执行成功
    3.dump执行成功
    4.成功
    5.restore成功
    6.restore成功
    7.成功
History     :
"""
import os
import time
import unittest
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro
Constant = Constant()


class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.common = Common()
        self.primary_root_node = Node('PrimaryRoot')
        self.primary_node = Node('PrimaryDbUser')
        self.comsh_p = CommonSH("PrimaryDbUser")
        self.dump_file = os.path.join(os.path.dirname(macro.DB_INSTANCE_PATH),
                                      'dump_case129')

    def test_gs_upgrade(self):
        text = '-----step1:创建序列 expect:成功-----'
        self.log.info(text)
        create_sql = 'drop sequence if exists dump_case0129;' \
                     'create sequence dump_case0129'
        create_res = self.comsh_p.execut_db_sql(create_sql)
        self.log.info(create_res)
        self.assertIn('CREATE SEQUENCE', create_res, '序列创建失败')
        mkdir_cmd = f'mkdir -p {self.dump_file}'
        self.log.info(mkdir_cmd)
        dir_res = self.common.get_sh_result(self.primary_node, mkdir_cmd)
        self.log.info(dir_res)

        text = '-----step2:第一次执行gs_dump postgres expect:成功-----'
        self.log.info(text)
        dump1_path = os.path.join(self.dump_file, 'dump1.sql')
        dump1_cmd = f'source {macro.DB_ENV_PATH};' \
                    f'gs_dump -p {self.primary_node.db_port} ' \
                    f'{self.primary_node.db_name} -f {dump1_path}'
        self.log.info(dump1_cmd)
        dump1_res = self.common.get_sh_result(self.primary_node, dump1_cmd)
        self.log.info(dump1_res)
        self.assertIn(f'dump database {self.primary_node.db_name} '
                      'successfully', dump1_res, '备份失败')

        text = '-----step3:再次次执行gs_dump postgres expect:成功-----'
        self.log.info(text)
        dump2_path = os.path.join(self.dump_file, 'dump2.sql')
        dump2_cmd = f'source {macro.DB_ENV_PATH};' \
                    f'gs_dump -p {self.primary_node.db_port} ' \
                    f'{self.primary_node.db_name} -f {dump2_path}'
        self.log.info(dump2_cmd)
        dump2_res = self.common.get_sh_result(self.primary_node, dump2_cmd)
        self.log.info(dump2_res)
        self.assertIn(f'dump database {self.primary_node.db_name} '
                      'successfully', dump1_res, '备份失败')

        text = '-----step4:修改序列值 expect:成功-----'
        self.log.info(text)
        sql = "select nextval('dump_case0129');select nextval('dump_case0129')"
        update_res = self.comsh_p.execut_db_sql(sql)
        self.log.info(update_res)
        self.assertEqual(2, update_res.count('nextval'), '修改序列值失败')

        text = '-----step5:执行gs_restore postgres expect:成功-----'
        self.log.info(text)
        dump1_tar_path = os.path.join(self.dump_file, 'dump1.tar')
        dump1_tar_cmd = f'source {macro.DB_ENV_PATH};' \
                        f'gs_dump -p {self.primary_node.db_port} ' \
                        f'{self.primary_node.db_name} -F t -f {dump1_tar_path}'
        self.log.info(dump1_tar_cmd)
        dump1_tar_res = self.common.get_sh_result(self.primary_node,
                                                  dump1_tar_cmd)
        self.log.info(dump1_tar_res)
        self.assertIn(f'dump database {self.primary_node.db_name} '
                      'successfully', dump1_tar_res, '备份失败')
        restore1_cmd = f'source {macro.DB_ENV_PATH};' \
                       f'gs_restore -U {self.primary_node.ssh_user} ' \
                       f'-W "{macro.COMMON_PASSWD}" ' \
                       f'-p {self.primary_node.db_port} ' \
                       f'-d {self.primary_node.db_name} {dump1_tar_path}'
        self.log.info(restore1_cmd)
        restore1_res = self.common.get_sh_result(self.primary_node,
                                                 restore1_cmd)
        self.log.info(restore1_res)
        self.assertIn('restore operation successful', restore1_res,
                      'restore失败')

        self.log.info('查看序列值')
        check1_res = self.comsh_p.execut_db_sql('select * from  dump_case0129')
        self.log.info(check1_res)

        text = '-----step6:再次执行gs_restore postgres expect:成功-----'
        self.log.info(text)
        dump2_tar_path = os.path.join(self.dump_file, 'dump2.tar')
        dump2_tar_cmd = f'source {macro.DB_ENV_PATH};' \
                        f'gs_dump -p {self.primary_node.db_port} ' \
                        f'{self.primary_node.db_name} -F t -f {dump2_tar_path}'
        self.log.info(dump2_tar_cmd)
        dump2_tar_res = self.common.get_sh_result(self.primary_node,
                                                  dump2_tar_cmd)
        self.log.info(dump2_tar_res)
        self.assertIn(f'dump database {self.primary_node.db_name} '
                      'successfully', dump2_tar_res, '备份失败')
        restore2_cmd = f'source {macro.DB_ENV_PATH};' \
                       f'gs_restore -U {self.primary_node.ssh_user} ' \
                       f'-W "{macro.COMMON_PASSWD}" ' \
                       f'-p {self.primary_node.db_port} ' \
                       f'-d {self.primary_node.db_name} {dump2_tar_path}'
        self.log.info(restore2_cmd)
        restore2_res = self.common.get_sh_result(self.primary_node,
                                                 restore2_cmd)
        self.log.info(restore2_res)
        self.assertIn('restore operation successful', restore2_res,
                      'restore失败')

        self.log.info('查看序列值')
        check2_res = self.comsh_p.execut_db_sql('select * from  dump_case0129')
        self.log.info(check2_res)
        self.assertEqual(check1_res, check2_res, '检查失败')

    def tearDown(self):
        text = "-----step7:恢复数据库，清理用户进程及文件 expect:成功-----"
        self.log.info(text)
        del_cmd = f'rm -rf {self.dump_file};' \
                  f'if [ -d {self.dump_file} ]; ' \
                  f'then echo "exists"; else echo "not exists"; fi'
        self.log.info(del_cmd)
        del_flag = False
        for count in range(10):
            del_res = self.common.get_sh_result(self.primary_root_node, del_cmd)
            if 'not exists' in del_res:
                del_flag = True
                break
        drop_res = self.comsh_p.execut_db_sql('drop sequence dump_case0129')
        self.log.info(drop_res)
        self.assertTrue(del_flag)
        self.assertIn('DROP SEQUENCE', drop_res, '序列创建失败')
        self.log.info(f'-----{os.path.basename(__file__)} finish-----')
